<template>
  <div class="app-container">
    <div class="container-left">
      <div>
        <el-input v-model="filterText" placeholder="请输入关键词搜索">
          <i slot="suffix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <div class="title">
          <span>公司名称</span> <span> ( {{ total }} )</span>
        </div>

        <div v-loading="listLoading">
          <el-tree
            :data="edc"
            :props="defaultProps"
            @node-click="handleNodeClick"
            node-key="id"
            :highlight-current="true"
            ref="tree"
            :filter-node-method="filterNode"
            :default-expanded-keys="expandDefault"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span class="custom-tree-node-span">{{ node.label }}</span>
            </span>
          </el-tree>
        </div>
      </div>
    </div>
    <div class="container-right">
      <div class="container-right-details">
        <el-row :gutter="10">
          <el-col :span="7"
            ><div class="grid-content bg-purple">
              公司名称：<i class="grid-details">{{
                formatText(currentNode.taxpayerName)
              }}</i>
            </div></el-col
          >
          <el-col :span="7"
            ><div class="grid-content bg-purple">
              纳税识别号：<i class="grid-details">{{
                formatText(currentNode.creditCode)
              }}</i>
            </div></el-col
          >
          <el-col :span="10"
            ><div class="grid-content bg-purple">
              注册地址：<i class="grid-details">{{
                formatText(currentNode.registerAddress)
              }}</i>
            </div></el-col
          >
        </el-row>
        <el-row :gutter="10">
          <el-col :span="7"
            ><div class="grid-content bg-purple">
              成立日期：<i class="grid-details">{{
                formatText(currentNode.registerTime, "date")
              }}</i>
            </div></el-col
          >
          <el-col :span="5"
            ><div class="grid-content bg-purple">
              成立时长：<i class="grid-details">{{
                formatText(currentNode.yearsDiff)
              }}</i
              ><i v-if="currentNode.yearsDiff" class="grid-details">年</i>
            </div></el-col
          >
          <el-col :span="7"
            ><div class="grid-content bg-purple">
              行业分类：<i class="grid-details">{{
                formatText(currentNode.industry)
              }}</i>
            </div></el-col
          >
          <el-col :span="5"
            ><div class="grid-content bg-purple">
              所属省份：<i class="grid-details">{{
                formatText(currentNode.provinceName)
              }}</i>
            </div></el-col
          >
        </el-row>
        <el-row :gutter="10">
          <el-col :span="7"
            ><div class="grid-content bg-purple">
              当前法人：<i class="grid-details">{{
                formatText(currentNode.legalPerson)
              }}</i>
            </div></el-col
          >
          <el-col :span="5"
            ><div class="grid-content bg-purple">
              法人变更：<i class="grid-details">{{
                formatText(currentNode.legalPersonChange)
              }}</i>
            </div></el-col
          >
          <el-col :span="7"
            ><div class="grid-content bg-purple">
              法人占股比例：<i class="grid-details">{{
                formatText(currentNode.legalPersonRatio)
              }}</i
              ><i v-if="currentNode.legalPersonRatio" class="grid-details">%</i>
            </div></el-col
          >
          <el-col :span="5"
            ><div class="grid-content bg-purple">
              客户经理：<i class="grid-details">{{
                formatText(currentNode.nickName)
              }}</i>
            </div></el-col
          >
        </el-row>
      </div>

      <div class="container-right-line">
        <taxline ref="invoiceLine"></taxline>
        <taxline ref="priseLine"></taxline>
      </div>
      <el-tabs v-model="activeName">
        <el-tab-pane label="纳税金额" name="first">
          <taxTable
            :currentId="currentNode.id"
            ref="taxpayref"
            taxname="taxpay"
          ></taxTable>
        </el-tab-pane>
        <el-tab-pane label="开票金额" name="second">
          <taxTable
            :currentId="currentNode.id"
            ref="amountref"
            taxname="amount"
          ></taxTable>
        </el-tab-pane>
        <el-tab-pane label="纳税信用" name="third">
          <taxInformation ref="inforef"></taxInformation>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import taxTable from "./components/taxTable.vue";
import taxline from "../../components/echarts/taxLine.vue";
import { deepClone } from "../../utils/deepclone";
import { getCreditStatusInfo } from "@/api/tax";
import {
  getlistEnterpriseInfo,
  getEnterpriseApplyAmount,
  getEnterprisePaidTaxesAmount
} from "../../../src/api/taxAnalysis";

import taxInformation from "./components/taxInformation.vue";

export default {
  components: {
    taxTable,
    taxline,
    taxInformation
  },
  data() {
    return {
      filterText: "",
      defaultProps: {
        children: "children",
        label: "taxpayerName"
      },

      expandDefault: [], //默认选中第一项

      edc: [],
      currentNode: {},
      activeName: "first",

      listLoading: false,
      total: null
    };
  },

  mounted() {
    this.init();
  },

  // 为了选中第一层级下的第一个节点
  watch: {
    expandDefault(newVal, oldVal) {
      if (newVal) {
        this.$nextTick(() => {
          document
            .querySelector(".el-tree-node__children .el-tree-node__content")
            .click();
        });
      }
    },

    filterText(val) {
      this.$refs.tree.filter(val);
      this.total = null;
      console.log(this.edc, "edc");
      this.$nextTick(() => {
        this.setCurrentData();
      });
      // this.init();
    }
  },

  methods: {
    setCurrentData() {
      const traverseNode = node => {
        if (Object.prototype.toString.call(node) === "[object Array]") {
          return node.map(t => traverseNode(t));
        }
        const data = {
          id: node.key,
          name: node.label,
          visible: node.visible,
          children: []
        };
        const childNodes = node.childNodes;
        childNodes.forEach(child => {
          const item = traverseNode(child);
          if (item.visible) {
            data.visible = true;
          }
          data.children.push(item);
        });
        return data;
      };
      const traverseVisible = arr => {
        return arr.filter(t => {
          let visible = t.visible;
          if (!visible) {
            return false;
          }
          if (t.children) {
            t.children = traverseVisible(t.children);
          }
          delete t.visible;
          return visible;
        });
      };
      const data = traverseNode(this.$refs.tree.store.root.childNodes);
      let current = traverseVisible(data);

      current.forEach(v => {
        v.name = v.name + "（" + v.children.length + "）";
      });
      console.log(current);

      // this.edc = current;
      // current.forEach(value => {
      //   if (current[value].length !== 0) {
      //     this.edc.push({
      //       taxpayerName: `${value}（${current[value].length}）`,
      //       children: deepClone(current[value])
      //     });
      //   }
      //   this.total += current[value].length;
      // });
    },

    filterNode(value, data) {
      let selectArr = ["taxpayerName", "creditCode", "legalPerson", "nickName"];
      if (!value) return true;
      if (!data.children) {
        return selectArr.some(item => {
          if (data[item]) {
            return data[item].indexOf(value) !== -1;
          } else {
            return false;
          }
        });
      }
    },

    init() {
      this.listLoading = true;
      getlistEnterpriseInfo()
        .then(res => {
          if (Object.keys(res.data).length !== 0) {
            Object.keys(res.data).forEach(value => {
              if (res.data[value].length !== 0) {
                this.edc.push({
                  taxpayerName: `${value}`,
                  num: `（${res.data[value].length}）`,
                  children: deepClone(res.data[value])
                });
              }
              this.total += res.data[value].length;
            });
            this.expandDefault.push(this.edc[0].children[0].id);
          }
          this.listLoading = false;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    handleNodeClick(data) {
      if (data.id) {
        this.currentNode = data;
        let applydata = {
          enterpriseId: this.currentNode.id,
          taxPeriodStart: "",
          taxPeriodEnd: ""
        };

        let taxesdata = {
          enterpriseId: this.currentNode.id,
          taxPeriodStartTime: "",
          taxPeriodEndTime: ""
        };
        this.getApplyAmountList(taxesdata);
        this.getEnterprisePaidTaxesAmount(applydata);

        this.$refs.inforef.getList(this.currentNode.id, false);
      }
    },

    getApplyAmountList(data) {
      this.$refs.priseLine.showLonding();

      this.$refs.amountref.showLoading();
      getEnterpriseApplyAmount(data)
        .then(res => {
          this.handelResult(res, "invoiceLine", "开票");
          this.$refs.amountref.ceatData(res, false);
          this.$refs.amountref.hideLoading();
        })
        .finally(() => {
          this.$refs.amountref.hideLoading();
        });
    },

    getEnterprisePaidTaxesAmount(data) {
      this.$refs.invoiceLine.showLonding();
      this.$refs.taxpayref.showLoading();

      getEnterprisePaidTaxesAmount(data)
        .then(res => {
          this.handelResult(res, "priseLine", "纳税");
          this.$refs.taxpayref.ceatData(res, false);
          this.$refs.taxpayref.hideLoading();
        })
        .finally(() => {
          this.$refs.taxpayref.hideLoading();
        });
    },

    async handelResult(res, linef, text) {
      if (res.data.paidTaxesDataList.length === 0) {
        this.$refs[linef].initCharts(0, `近三年${text}总金额`);
        return;
      }

      let echartsArr = [];
      let legend = [];
      res.data.paidTaxesDataList.forEach(item => {
        let arr = [];
        item.monthData.forEach(val => {
          arr.push(val.value);
        });
        echartsArr.push(arr);
        legend.push(item.year);
      });

      legend = legend.sort().reverse();
      this.$refs[linef].initCharts(echartsArr, `近三年${text}总金额`, legend);
    },

    formatText(Text, date) {
      if (date === "date") {
        return Text ? Text.split(" ")[0] : "-";
      }
      return Text ? Text : "-";
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-tree-node__content {
  height: 36px;
}

/deep/ .el-tree-node__label {
  white-space: nowrap; //不换行
  overflow: hidden; //超出部分隐藏
  text-overflow: ellipsis; //文本溢出显示省略号
}

.app-container {
  display: flex;
  background-color: #f5f5f5;
  .container-left {
    width: 300px;
    height: calc(100vh - 70px);
    overflow-y: scroll;
    padding: 32px 10px 10px;
    background-color: #fff;
    margin-right: 20px;

    .title {
      margin: 24px 6px 20px;
      font-weight: bold;
      font-size: 16px;
      color: #999999;
    }
  }
  .container-right {
    width: 100%;
    overflow: hidden;
    background-color: #fff;
    padding: 16px;

    .container-right-details {
      background-color: #f3f3f3;
      font-size: 16px;
      color: #555555;
      border-radius: 4px;
      padding: 6px 32px;
      margin-bottom: 32px;

      .grid-details {
        font-weight: bold;
        color: #222222;
        font-style: normal;
      }
    }
    .el-row {
      // margin-bottom: 8px;
      &:last-child {
        margin-bottom: 0;
      }
    }
    .grid-content {
      min-height: 36px;
      line-height: 36px;
    }
    .row-bg {
      padding: 10px 0;
      background-color: #f9fafc;
    }

    .container-right-line {
      width: 100%;
      display: flex;
      justify-content: space-around;
    }
  }
}
</style>
